package com.hundsun.yr.universal.library.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.gyf.barlibrary.ImmersionBar;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.loading.VaryViewHelperController;
import com.hundsun.yr.universal.library.widget.HSToast;

import java.lang.reflect.Field;

import de.greenrobot.event.EventBus;



/**
 * @Title: BaseLazyFragment.java 
 * @Description: TODO(用一句话描述该文件做什么) 
 * @date 2015-10-15 下午3:54:38 
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com 
 * @replace author:
 * @replace date:
 * @version V1.0   
 */
public abstract class BaseLazyFragment extends Fragment{
	/**
	 * 自定义Toast
	 */
	private HSToast hsToast;
    /**
     * Log tag
     */
    protected static String TAG_LOG = null;

    /**
     * 屏幕信息
     */
    protected int mScreenWidth = 0;
    protected int mScreenHeight = 0;
    protected float mScreenDensity = 0.0f;

    protected Context mContext = null;

    private boolean isFirstResume = true;
    private boolean isFirstVisible = true;
    private boolean isFirstInvisible = true;
    private boolean isPrepared;

    private VaryViewHelperController mVaryViewHelperController = null;
    private ImmersionBar mImmersionBar;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mContext = activity;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TAG_LOG = this.getClass().getSimpleName();
        if (isBindEventBusHere()) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (getContentViewLayoutID() != 0) {
            return inflater.inflate(getContentViewLayoutID(), null);
        } else {
            return super.onCreateView(inflater, container, savedInstanceState);
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        

        DisplayMetrics displayMetrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

        mScreenDensity = displayMetrics.density;
        mScreenHeight = displayMetrics.heightPixels;
        mScreenWidth = displayMetrics.widthPixels;

        
        
        if (null != getLoadingTargetView()) {
            mVaryViewHelperController = new VaryViewHelperController(getLoadingTargetView());
        }
        initViewsAndEvents();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (isBindEventBusHere()) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        // for bug ---> java.lang.IllegalStateException: Activity has been destroyed
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);

        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initPrepare();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isFirstResume) {
            isFirstResume = false;
            return;
        }
        if (getUserVisibleHint()) {
            onUserVisible();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getUserVisibleHint()) {
            onUserInvisible();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (isFirstVisible) {
                isFirstVisible = false;
                initPrepare();
            } else {
                onUserVisible();
            }
        } else {
            if (isFirstInvisible) {
                isFirstInvisible = false;
                onFirstUserInvisible();
            } else {
                onUserInvisible();
            }
        }
    }

    private synchronized void initPrepare() {
    	
        if (isPrepared) {
            onFirstUserVisible();
        } else {
            isPrepared = true;
        }
    }
    
    /**
     * 设置显示的layout
     *
     * @return layout的id资源
     */
    protected abstract int getContentViewLayoutID();
    /**
     * 加载试图绑定事件
     */
    protected abstract void initViewsAndEvents();
    
    /**
     * fragment第一次显示时调用，可以用来显示加载刷新数据 
     */
    protected abstract void onFirstUserVisible();

    /**
     * 相当于fragment的onResume()
     */
    protected abstract void onUserVisible();

    /**
     * fragment第一次显示时调用
     */
    private void onFirstUserInvisible() {
        // here we do not recommend do something
    }

    /**
     * 相当于fragment的onPause()
     */
    protected abstract void onUserInvisible();

    /**
     * 显示loadingview的视图
     */
    protected abstract View getLoadingTargetView();

    /**
     * 当事件 eventBus 传递过来
     *
     * @param eventCenter
     */
    @SuppressWarnings("rawtypes")
	protected abstract void onEveComming(EventCenter eventCenter);

    /**
     * 是否绑定 eventBus事件
     *
     * @return
     */
    protected abstract boolean isBindEventBusHere();

    /**
     * get the support fragment manager
     *
     * @return
     */
    protected FragmentManager getSupportFragmentManager() {
        return getActivity().getSupportFragmentManager();
    }

    /**
     * 跳转Activity
     *
     * @param clazz
     */
    protected void readyGo(Class<?> clazz) {
        Intent intent = new Intent(getActivity(), clazz);
        startActivity(intent);
    }

    /**
     * 跳转Activity并传递bundle
     *
     * @param clazz
     * @param bundle
     */
    protected void readyGo(Class<?> clazz, Bundle bundle) {
        Intent intent = new Intent(getActivity(), clazz);
        if (null != bundle) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * 跳转Activity并获取返回值
     *
     * @param clazz
     * @param requestCode
     */
    protected void readyGoForResult(Class<?> clazz, int requestCode) {
        Intent intent = new Intent(getActivity(), clazz);
        startActivityForResult(intent, requestCode);
    }

    /**
     * 跳转Activity并获取返回值并传递bundle
     *
     * @param clazz
     * @param requestCode
     * @param bundle
     */
    protected void readyGoForResult(Class<?> clazz, int requestCode, Bundle bundle) {
        Intent intent = new Intent(getActivity(), clazz);
        if (null != bundle) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    /**
     * 弹出 Snackbar
     *
     * @param msg
     */
    protected void showSnackbar(String msg) {
        //防止遮盖虚拟按键
        if (null != msg && !TextUtils.isEmpty(msg)) {
            Snackbar.make(getLoadingTargetView(), msg, Snackbar.LENGTH_SHORT).show();
        }
    }
    
    /**
	 * 弹出Toast
	 * @param resId Toast文字资源ID
	 */
    protected void showToast(int resId) {
    	if(hsToast==null)hsToast=new HSToast(mContext);
    	hsToast.showSingletonToast(resId);
    }
    /**
	 * 弹出Toast
	 * @param text Toast文字内容
	 */
    protected void showToast(String text) {
    	if(text==null)return;
    	if(hsToast==null)hsToast=new HSToast(mContext);
    	hsToast.showSingletonToast(text);
    }

    /**
     * 显示loading视图
     *
     * @param toggle
     */
    protected void toggleShowLoading(boolean toggle, String msg) {
        if (null == mVaryViewHelperController) {
            throw new IllegalArgumentException("You must return a right target view for loading");
        }

        if (toggle) {
            mVaryViewHelperController.showLoading(msg);
        } else {
            mVaryViewHelperController.restore();
        }
    }

    /**
     * 显示空视图
     *
     * @param toggle
     */
    protected void toggleShowEmpty(boolean toggle, int drawableRes,String msg, View.OnClickListener onClickListener) {
        if (null == mVaryViewHelperController) {
            throw new IllegalArgumentException("You must return a right target view for loading");
        }

        if (toggle) {
            mVaryViewHelperController.showEmpty(drawableRes,msg, onClickListener);
        } else {
            mVaryViewHelperController.restore();
        }
    }

    /**
     * 显示错误视图
     *
     * @param toggle
     */
    protected void toggleShowError(boolean toggle, String msg, View.OnClickListener onClickListener) {
        if (null == mVaryViewHelperController) {
            throw new IllegalArgumentException("You must return a right target view for loading");
        }

        if (toggle) {
            mVaryViewHelperController.showError(msg, onClickListener);
        } else {
            mVaryViewHelperController.restore();
        }
    }

    /**
     * 显示网络错误视图
     *
     * @param toggle
     */
    protected void toggleNetworkError(boolean toggle, View.OnClickListener onClickListener) {
        if (null == mVaryViewHelperController) {
            throw new IllegalArgumentException("You must return a right target view for loading");
        }

        if (toggle) {
            mVaryViewHelperController.showNetworkError(onClickListener);
        } else {
            mVaryViewHelperController.restore();
        }
    }

    @SuppressWarnings("rawtypes")
	public void onEventMainThread(EventCenter eventCenter) {
        if (null != eventCenter) {
            onEveComming(eventCenter);
        }
    }
    
    
    /**
     * 通过泛型来简化findViewById
     */
    @SuppressWarnings("unchecked")
	protected final <E extends View> E findView(int id) {
        try {
            return (E) getActivity().findViewById(id);
        } catch (ClassCastException ex) {
            Log.e(TAG_LOG, "Could not cast View to concrete class.", ex);
            throw ex;
        }
    }
    
    /**
     * 通过泛型来简化findViewById
     */
    @SuppressWarnings("unchecked")
	protected final <E extends View> E findView(View view,int id) {
        try {
            return (E) view.findViewById(id);
        } catch (ClassCastException ex) {
            Log.e(TAG_LOG, "Could not cast View to concrete class.", ex);
            throw ex;
        }
    }

}
